using System.Collections.Generic;
using UnityEngine;

namespace WorldMapBase.Tile.Pool
{
    public class CommonPrefabPool: ObjectPool<Transform>
    {
        private int _initNum;
        protected GameObject _originObject;
        protected Transform _root;

        protected List<Transform> _allItems;
        
        public CommonPrefabPool(int initNum, int capacity, GameObject originObject,Transform root) : base(capacity)
        {
#if UNITY_EDITOR
            _name = "通用对象池: " + originObject.name;
#endif
            
            _initNum = initNum;
            _originObject = originObject;
            _root = root;
            _allItems = new List<Transform>(capacity);
            OnInit(_initNum);
        }

        public CommonPrefabPool(
            int initNum, 
            int capacity, 
            GameObject originObject, 
            Transform root,
            bool enableAutoShrink, 
            int idleMaxCount, 
            int frameShrinkCount, 
            float shrinkIntervalTime):
            base(capacity, enableAutoShrink, idleMaxCount, frameShrinkCount, shrinkIntervalTime)
        {
#if UNITY_EDITOR
            _name = "通用对象池: " + originObject.name;
#endif
            
            _initNum = initNum;
            _originObject = originObject;
            _root = root;
            _allItems = new List<Transform>(capacity);
            OnInit(_initNum);
        }
        
        protected override Transform ConstructItem()
        {
            if (_originObject == null)
            {
                UnityEngine.Debug.LogError("DynamicPrefabPool ConstructItem _originObject is nil");
                return null;
            }
            
            Transform objTransform = 
                GameObject.Instantiate(_originObject, GlobalValue.INVISIBLE_POSITION, Quaternion.identity,WorldDynamicPoolMgr.InstanceRoot).transform;

            objTransform.parent = _root;
            objTransform.position = GlobalValue.INVISIBLE_POSITION;
            _allItems.Add(objTransform);
            return objTransform;
        }
        
        protected override void BeforeRecover(Transform obj)
        {
            obj.position = GlobalValue.INVISIBLE_POSITION;
        }

        protected override void OnRemoveItem(Transform trans)
        {
            if (trans)
            {
                GameObject.Destroy(trans.gameObject);
            }
        }

        public override void Destroy()
        {
            foreach (var item in _allItems)
            {
                if (item)
                {
                    GameObject.DestroyImmediate(item.gameObject);
                }   
            }
            _allItems.Clear();
            base.Destroy();
            _originObject = null;
        }
    }
}